package edu.hut.bookshop.Alipay;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import edu.hut.bookshop.config.AlipayConfig;
import edu.hut.bookshop.pojo.Pay;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

//支付宝接口
@Component
public class Alipay {

    public String pay(String sn, BigDecimal totalAmount,String title)throws AlipayApiException{
        //1.获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //2.设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        //页面跳转同步通知页面路径
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        //页面跳转异步通知页面路径
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        System.out.println(sn+","+totalAmount+","+title);
        //将数据封装到一个集合中
        Map<String, String> param = new HashMap<String, String>();
        //商户订单号，商户网站订单系统中唯一订单号，必填
        param.put("out_trade_no", sn);
        //付款金额，必填
        param.put("total_amount", totalAmount.toString());
        //订单名称，必填
        param.put("subject", title);
        param.put("product_code", "FAST_INSTANT_TRADE_PAY");
        //封装参数
        alipayRequest.setBizContent(JSONObject.toJSONString(param));
        //请求支付宝进行付款，并获取支付结果
        String html = null;
        try {
            //请求
            html = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //返回付款信息
        return html;
    }


    /**
     * 验证支付宝异步通知签名是否合法
     * @param
     * @return
     */
    public static boolean isValid(HttpServletRequest request){
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        System.out.println(JSONObject.toJSONString(params));
        try {
            return AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
        } catch (AlipayApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } //调用SDK验证签名
        return false;
    }
}
